using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using  RFCard;
using JHVideo;
using LED;
using System.IO;
using Weight.Base;
using PlateNumVideo.Interface;
using PlateNumVideo;
using PlateNumVideo.Entity;

namespace DeviceManager
{
    /// <summary>
    /// 设备管理器
    /// </summary>
    public class DeviceManagers: IDevManager
    {
        /// <summary>
        /// 读卡器
        /// </summary>
        private Dictionary<CardType, List<ICard>> mCards = new Dictionary<CardType, List<ICard>>();
        /// <summary>
        /// LED数字屏
        /// </summary>
        private List<ILED> mLeds =new List<ILED>();

        /// <summary>
        /// 车号
        /// </summary>
        private List<IPlateNumVideo> mPlateNum = new List<IPlateNumVideo>();
        /// <summary>
        /// 监控
        /// </summary>
        private IVideo mVideo;

        /// <summary>
        /// 车号识别
        /// </summary>
        private List<IPlateNumVideo> plateNumVideos;

        /// <summary>
        /// 设备参数
        /// </summary>
        private DevParam mDevParam;

        /// <summary>
        /// 记录串口对应的设备
        /// </summary>
        private Dictionary<string, string> mPortInfo = new Dictionary<string, string>();
        /// <summary>
        /// 构造
        /// </summary>
        public DeviceManagers(DevParam devParam)
        {
            mDevParam = devParam;
            AddEnvironmentPaths();
        }


        #region 加载环境变量

        /// <summary>
        ///获取设备路径
        /// </summary>
        /// <returns></returns>
        private IEnumerable<string> GetPaths()
        {
            string rootPath = Environment.CurrentDirectory + "/DeviceDLL";
            string[] paths = Directory.GetDirectories(rootPath);
            List<string> list = new List<string>();
            list.Add(rootPath);
            foreach (string item in paths)
            {
                string[] subPaths = Directory.GetDirectories(item);
                if (subPaths.Length > 0)
                {
                    list.AddRange(subPaths);
                }
            }
            return list.ToArray();
        }

        /// <summary>
        /// 添加环境变量
        /// </summary>
        /// <param name="paths"></param>
        private  void AddEnvironmentPaths()
        {
            IEnumerable<string> paths = GetPaths();
            var path = new[] { Environment.GetEnvironmentVariable("PATH") ?? string.Empty };
            string newPath = string.Join(Path.PathSeparator.ToString(), path.Concat(paths));
            Environment.SetEnvironmentVariable("PATH", newPath);
        }

        #endregion  加载环境变量

        #region 设备初始化
        /// <summary>
        /// 初始化
        /// </summary>
        /// <returns></returns>
        public ResultEntity init()
        {
            var result = ResultEntity.Default();
            try
            {
                StringBuilder contentBuider = new StringBuilder("设备初始化\r\n");
                if (mDevParam != null)
                {
                    bool b = true;
                    //读卡器
                    ICard card;
                    foreach (CardParam item in mDevParam.mCardParams)
                    {
                        if (item.IsUse)
                        {
                            card = CardFactory.CreateCardFactory(item.DevType);
                            if(!mCards.Keys.Contains(item.DevType))
                            {
                                List<ICard> list = new List<ICard>();
                                list.Add(card);
                                mCards.Add(item.DevType, list);
                            }
                            else
                            {
                                mCards[item.DevType].Add(card) ;
                            }
                            ResultEntity res = card.Init();
                            if (res.State == 1)
                            {
                                contentBuider.Append(item.DevType.ToString()).Append("读卡器初始化成功，说明:").Append(res.Message).Append(";\r\n");
                            }
                            else
                            {
                                b = false;
                                contentBuider.Append(item.DevType.ToString()).Append("读卡器初始化失败，说明:").Append(res.Message).Append(";\r\n");
                            }
                        }
                    }

                    //LED 数字屏
                    ILED led;
                    foreach (LedParam item in mDevParam.mLedParams)
                    {
                        if (item.IsUse)
                        {
                            led = LedFactory.CreateFactory(item.DevType);
                            mLeds.Add(led);
                            contentBuider.Append("LED型号(" + item.DevType.ToString() + ") 初始化成功,说明：该设备不需要初始化;\r\n");
                        }
                    }

                    //监控
                    if (mDevParam.mVideoParam.IsUse)
                    {
                        mVideo = VideoFactory.CreateVideo(mDevParam.mVideoParam.DevType);
                        var rs = mVideo.Init();
                        if (rs.State == 1)
                        {
                            contentBuider.Append(mDevParam.mVideoParam.DevType.ToString()).Append("监控初始化成功，说明:").Append(rs.Message).Append(";\r\n");
                        }
                        else
                        {
                            contentBuider.Append(mDevParam.mVideoParam.DevType.ToString()).Append("监控初始化失败，说明:").Append(rs.Message).Append(";\r\n");
                            b = false;
                        }
                    }

                    //车号识别
                    IPlateNumVideo plateNumVideo;
                    if(mDevParam.plateRecParam != null)
                    {
                        foreach (var item in mDevParam.plateRecParam)
                        {
                            if (item.IsUse)
                            {
                                plateNumVideo = PlateNumFactory.CreateFactory(item.DevType);
                                if (plateNumVideo != null)
                                {
                                    plateNumVideo.Init(item.InitParam);
                                    mPlateNum.Add(plateNumVideo);
                                }
                            }
                        }
                    }
                  

                    if (b)
                    {
                        result = ResultEntity.Success(contentBuider.ToString());
                    }
                    else
                    {
                        result = ResultEntity.Error(contentBuider.ToString());
                    }
                }
                else
                {
                    result = ResultEntity.Error("无效的初始化参数!\r\n");
                }
            }
            catch (Exception ex)
            {
                result = ResultEntity.Error(ex.Message + ";" + ex.StackTrace);
            }
            return result;
        }

        #endregion 设备初始化

        #region 打开设备
        /// <summary>
        /// 打开设备
        /// </summary>
        /// <returns></returns>
        public ResultEntity<DevState> Open()
        {
            DevState deviceState = new DevState();
            var result = ResultEntity<DevState>.Default(deviceState, "执行设备打卡功能。\r\n");
            try
            {
                if (mDevParam != null)
                {
                    ResultEntity r1=  openCard(mDevParam.mCardParams);
                    deviceState.CardState = new CardResult()
                    {
                        Result = r1.State == 1 ? true : false,
                        Msg = r1.Message
                    };

                    ResultEntity r2 = openLed(mDevParam.mLedParams);
                    deviceState.LEDState = new LEDResult()
                    {
                        Result = r2.State == 1 ? true : false,
                        Msg = r2.Message
                    };

                    ResultEntity r3 = openVideo(mDevParam.mVideoParam);
                    deviceState.VideoState = new VideoResult()
                    {
                        Result = r3.State == 1 ? true : false,
                        Msg = r3.Message
                    };

                    ResultEntity r4 = OpenPlateVideo();

                    result = ResultEntity<DevState>.Success(deviceState, "执行成功!\r\n");
                }
                else
                {
                    deviceState.CardState = new CardResult()
                    {
                        Result = false,
                        Msg = "未初始化的设备参数\r\n"
                    };

                    deviceState.LEDState = new LEDResult()
                    {
                        Result = false,
                        Msg = "未初始化的设备参数\r\n"
                    };

                    deviceState.VideoState = new VideoResult()
                    {
                        Result = false,
                        Msg = "未初始化的设备参数\r\n"
                    };
                    result = ResultEntity<DevState>.Error(deviceState, "设备参数无初始化!\r\n");
                }
            }
            catch(Exception ex)
            {
                result = ResultEntity<DevState>.Error(deviceState, "打开设备异常:" + ex.Message + "，堆栈信息:" + ex.Message + "\r\n");
            }
            return result;
        }

        /// <summary>
        /// 打开射频卡
        /// </summary>
        /// <param name="cardParams"></param>
        /// <returns></returns>
        private  ResultEntity openCard(List<CardParam> cardParams)
        {
            var result = ResultEntity.Default();
            StringBuilder logBuider = new StringBuilder();
            bool b = true;
            try
            {
                ResultEntity res;
                CardParam cardParam;
                string port = string.Empty;
                string name = string.Empty;
                foreach(KeyValuePair<CardType,List<ICard>> item in mCards)
                {
                    name = CardTypeNameHelper.GetCardTypeName(item.Key); 
                    var CardConfigs = cardParams.Where(p=>p.DevType == item.Key).ToList();
                    //判断参数是否有效
                    if (CardConfigs.Count == 0)
                    {
                        logBuider.Append("射频卡("+ name + ")设备参数错误:无设置参数。\r\n");
                        b = false;
                    }

                    //if (CardConfigs.Count != item.Value.Count)
                    //{
                    //    logBuider.Append("射频卡("+ name + ")设备参数错误：使用设备的个数和参数的个数不配。\r\n");
                    //    b = false;
                    //    continue;
                    //}
                    for (int index = 0; index < item.Value.Count; index++)
                    {
                        cardParam = CardConfigs[index];
                        port = cardParam.initParam.Port.ToString();
                        if (mPortInfo.Keys.Contains(port))
                        {
                            logBuider.Append("射频卡("+ name + ")状态:串口" + port + "已被占用,").Append("说明:").Append(mPortInfo[port]).Append("已打开此串口;\r\n");
                            b = false;
                            continue;
                        }
                        else
                        {
                            logBuider.Append("射频卡(" + name + ")设备:索引[" + index + "]/型号[" + cardParam.DevType).Append("],");
                            res = item.Value[index].Open(cardParam.initParam);
                            if (res.State == 1)
                            {
                                logBuider.Append("状态:打开成功,").Append("说明:").Append(res.Message).Append("\r\n");
                                mPortInfo.Add(cardParam.initParam.Port.ToString(), "设备索引:" + index + ", 设备型号:" + cardParam.DevType);
                                if(cardParam.SetStatus != null)
                                {
                                    cardParam.SetStatus(item.Key, cardParam.DevNo, true);
                                }
                            }
                            else
                            {
                                logBuider.Append("状态:打开失败,").Append("说明:").Append(res.Message).Append("\r\n");
                                b = false;
                                if(cardParam.SetStatus != null)
                                {
                                    cardParam.SetStatus(item.Key, cardParam.DevNo, false);
                                }
                                continue;
                            }
                        }

                        logBuider.Append("占用串口:").Append(cardParam.initParam.Port).Append("，")
                        .Append("波特率:").Append(cardParam.initParam.BaudRate).Append("。\r\n");
                    }
                }
      

                if(b)
                {
                    result = ResultEntity.Success(logBuider.ToString());
                }
                else
                {
                    result = ResultEntity.Error(logBuider.ToString());
                }
            }
            catch (Exception ex)
            {
                result = ResultEntity.Error("射频卡打开功能异常:"+ex.Message + ",错误信息:" + ex.StackTrace+"\r\n");
            }

            return result;
        }


        /// <summary>
        /// 打开LED设备
        /// </summary>
        /// <param name="ledParams"></param>
        /// <returns></returns>
        private ResultEntity openLed(List<LedParam> ledParams)
        {
            var result = ResultEntity.Default();
            StringBuilder logBuider = new StringBuilder();
            bool b = true;
            try
            {
                //判断参数是否有效
                if (mLeds.Count > 0)
                {
                    if (ledParams == null || ledParams.Count == 0 )
                    {
                        logBuider.Append("LED 参数错误:没有设置参数。\r\n");
                        b = false;
                    }
                    else if (ledParams.Count != mLeds.Count)
                    {
                        logBuider.Append("LED 参数错误：使用设备的个数和参数的个数不配。\r\n");
                        b = false;
                    }

                    if(!b)
                    {
                        result = ResultEntity.Error(logBuider.ToString());
                        return result;
                    }
                }

                //打开设备
                LedParam ledParam;
                ILED ledDev;
                ResultEntity res;
                for (int index = 0; index < mLeds.Count; index++)
                {
                    ledDev = mLeds[index];
                    ledParam = ledParams[index];
                    logBuider.Append("电子屏设备:LED索引[").Append(index).Append("]/型号[").Append(ledParam.DevType.ToString()).Append("],\r\n");
                    res = ledDev.Open(ledParam.InitParam);
                    if(res.State == 1)
                    {
                        logBuider.Append("状态:LED 打开成功，说明:").Append(res.Message).Append("\r\n");
                        if(ledParam.SetStatus != null)
                        {
                            ledParam.SetStatus(ledParam.DevNo,true);
                        }
                    }
                    else
                    {
                        logBuider.Append("状态:LED 打开失败，说明:").Append(res.Message).Append("\r\n");
                        b = false;
                        if (ledParam.SetStatus != null)
                        {
                            ledParam.SetStatus(ledParam.DevNo, false);
                        }
                        continue;
                    }

                    logBuider.Append("占用串口:").Append(ledParam.InitParam.Port).Append("或IP地址:").Append(ledParam.InitParam.Ip).Append(",\r\n");
                    logBuider.Append("波特率:").Append(ledParam.InitParam.Baudrate).Append("。\r\n");
                }

                if (!b)
                {
                    result = ResultEntity.Error(logBuider.ToString());
                }
                else
                {
                    result = ResultEntity.Success(logBuider.ToString());
                }
            }
            catch(Exception ex)
            {
                result = ResultEntity.Error("LED 打开功能异常:" + ex.Message + ",错误信息:" + ex.StackTrace + "。\r\n");
            }
            return result;
        }

        
        /// <summary>
        /// 打开监控模式
        /// </summary>
        /// <param name="videoParam"></param>
        /// <returns></returns>
        private ResultEntity openVideo(VideoParam videoParam )
        {
            var result = ResultEntity.Default();
            StringBuilder logBuider = new StringBuilder();
            try
            {
               //参数判断
               if(videoParam == null)
                {
                    logBuider.Append("监控参数错误:没有设置参数\r\n");
                    result = ResultEntity.Error(logBuider.ToString());
                }
               else
                {
                    if(mVideo != null)
                    {
                        result= mVideo.Login(videoParam.LoginParams);
                    }
                }
            }
            catch(Exception ex)
            {
                result = ResultEntity.Error("监控视频 打开功能异常:" + ex.Message + ",错误信息:" + ex.StackTrace + "\r\n");
            }
            return result;
        }

        /// <summary>
        /// 打开车号识别
        /// </summary>
        /// <returns></returns>
        private ResultEntity OpenPlateVideo()
        {
            var result = ResultEntity.Default();
            bool b = true;
            StringBuilder logBuider = new StringBuilder();
            try
            {
                for (int index = 0; index < mPlateNum.Count; index++)
                {
                    var plate = mPlateNum[index];
                    if(plate != null)
                    {
                       var res =  plate.Open();
                        if(res.Item1)
                        {
                            logBuider.Append("车号识别设备:设备索引号[" + index+ "]打开成功；\r\n");
                            var playRes = plate.StartRealPlay();
                            if(playRes.Item1)
                            {
                                logBuider.Append("车号识别设备:设备索引号[" + index + "]预览成功；\r\n");
                            }
                            else
                            {
                                logBuider.Append("车号识别设备:设备索引号[" + index + "]预览失败；\r\n");
                            }
                        }
                        else
                        {
                            b = false;
                            logBuider.Append("车号识别设备:设备索引号[" + index + "]打开失败，消息:"+ res.Item2 + ";\r\n");
                        }
                    }
                    else
                    {
                        b = false;
                        logBuider.Append("车号识别设备:设备索引号[" + index + "]无实例;\r\n");
                    }
                }

                if(b)
                {
                    result = ResultEntity.Error(logBuider.ToString());
                }
                else
                {
                    result = ResultEntity.Success(logBuider.ToString());
                }
            
            }
            catch (Exception ex)
            {
                result = ResultEntity.Error("车号识别打开功能异常:" + ex.Message + ",错误信息:" + ex.StackTrace + "\r\n");
            }
            return result;
        }

        #endregion  打开设备

        #region 关闭设备
        /// <summary>
        /// 关闭设备
        /// </summary>
        /// <returns></returns>
        public ResultEntity CloseDevice()
        {
            var result = ResultEntity.Default();
            StringBuilder logBuider = new StringBuilder();
            try
            {
                ResultEntity rs;
                bool b = true;
                string name = string.Empty;
                foreach (KeyValuePair<CardType,List<ICard>> item in mCards)
                {
                    name = CardTypeNameHelper.GetCardTypeName(item.Key);
                    int index = 1;
                    foreach(var it in item.Value)
                    {
                        if(it  != null)
                        {
                            rs =  it.Close();
                            if (rs.State == 1)
                            {
                                logBuider.Append("索引[").Append(index).Append("]的("+name+")射频卡关闭成功。").Append("\r\n");
                            }
                            else
                            {
                                logBuider.Append("索引[").Append(index).Append("]的(" + name + ")射频卡关闭失败,返回结果:").Append(rs.Message).Append("。\r\n");
                                b = false;
                            }
                        }
                        index++;
                    }
                }
        

                ///关闭LED 
                for(int index=0; index < mLeds.Count; index++)
                {
                    rs = mLeds[index].Close();
                    if (rs.State == 1)
                    {
                        logBuider.Append("索引[").Append(index).Append("]LED屏关闭成功。\r\n");
                    }
                    else
                    {
                        logBuider.Append("索引[").Append(index).Append("]的LED屏关闭失败,返回结果:").Append(rs.Message).Append("。\r\n") ;
                        b = false;
                    }
                }

                //关闭监控
                if(mVideo != null)
                {
                    rs = mVideo.Close();
                    if(rs.State == 1)
                    {
                        logBuider.Append("监控关闭成功。\r\n");
                    }
                    else
                    {
                        logBuider.Append("监控关闭失败，失败信息:").Append(rs.Message).Append("。\r\n");
                        b = false;
                    }
                }

                // 关闭车号识别
                if(mPlateNum != null)
                {
                    for (int index = 0; index < mPlateNum.Count; index++)
                    {
                        var plate = mPlateNum[index];
                        if(plate != null)
                        {
                            var res= plate.Close();
                            if (res.Item1)
                            {
                                logBuider.Append("索引[").Append(index).Append("]LED屏关闭成功。\r\n");
                            }
                            else
                            {
                                b = false;
                                logBuider.Append("索引[").Append(index).Append("]LED屏关闭失败。\r\n");
                            }
                        }
                    }
                }

                if(!b)
                {
                    result = ResultEntity.Success(logBuider.ToString());
                }
                else
                {
                    result = ResultEntity.Error(logBuider.ToString());
                }
            }
            catch(Exception ex)
            {
                logBuider.Append("关闭设备异常,错误:").Append(ex.Message).Append("，详细信息:").Append(ex.StackTrace);
                result = ResultEntity.Error(logBuider.ToString());
            }

            return result;
        }
        #endregion 关闭设备

        #region 抓拍图片
        /// <summary>
        /// 抓拍图片
        /// </summary>
        /// <param name="entity">抓拍参数</param>
        /// <returns></returns>
        public ResultEntity CaptureImg(CaptureParamEntity entity)
        {
            var result = ResultEntity.Default("开始抓拍图片!");
            try
            {
                if (mVideo != null)
                {
                    if(entity != null)
                    {
                       result =  mVideo.CaptureImg(entity);
                    }
                    else
                    {
                        result = ResultEntity.Error("没有设置抓拍图片参数!");
                    }
                }
                else
                {
                    result = ResultEntity.Error("没有开启监控设备功能，抓拍失败!");
                }
            }
            catch(Exception ex)
            {
                result = ResultEntity.Error("抓拍异常,异常信息："+ex.Message+",堆栈消息:"+ex.StackTrace);
            }
            return result;
        }

        #endregion  抓拍图片

        #region 获取卡号
        /// <summary>
        /// 获取卡号
        /// </summary>
        /// <param name="index">设备索引</param>
        /// <returns></returns>
        public ResultEntity<ResultValEntity> GetCardNo(CardType cardType,int index)
        {
            ResultValEntity entity = new ResultValEntity();
            var result = ResultEntity<ResultValEntity>.Default(entity, "开始读取卡号");
            string  name = CardTypeNameHelper.GetCardTypeName(cardType);
           
            try
            {
                if (!mCards.Keys.Contains(cardType))
                {
                    result = ResultEntity<ResultValEntity>.Error(entity, "(" + name + ")读卡设备功能未开启，获取卡号失败!");
                    return result;
                }
                else
                {
                    var cards = mCards[cardType];
                    if (cards.Count == 0)
                    {
                        result = ResultEntity<ResultValEntity>.Error(entity, "(" + name + ")读卡设备功能未开启，获取卡号失败!");
                    }
                    else
                    {
                        if (index >= cards.Count)
                        {
                            result = ResultEntity<ResultValEntity>.Error(entity, "设备索引[" + index + "]大于实际设备数,获取卡号失败!");
                        }
                        else
                        {
                            ICard card = cards[index];
                            result = card.GetCardNo();
                        }
                    }
                }
            
            }
            catch(Exception ex)
            {
                result = ResultEntity<ResultValEntity>.Error(entity, "获取卡号异常，异常信息:" + ex.Message + ";堆栈消息:" + ex.StackTrace);
            }

            return result;
        }

        #endregion 获取卡号

        #region 车号识别获取车号、抓拍图片

        /// <summary>
        /// 获取车号
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public ResultEntity<PlateNumRes> GetPlateNum(int index)
        {
            PlateNumRes entity = new PlateNumRes();
            var result = ResultEntity<PlateNumRes>.Default(entity, "开始读取车号");
            if (index < 0 || index >= mPlateNum.Count)
            {
                result = ResultEntity<PlateNumRes>.Error(entity, "索引错误,获取车号失败!");
            }
            else
            {
                if (mPlateNum.Count == 0)
                {
                    result = ResultEntity<PlateNumRes>.Error(entity, "索引错误,获取车号失败!");
                }
                else
                {
                    var plateVideo = mPlateNum[index];
                    var plateNumInfo =  plateVideo.GetPlateNum();
                    result = ResultEntity<PlateNumRes>.Success(plateNumInfo, plateNumInfo?.PlateNum);
                }
            }

            return result;
        }


        /// <summary>
        /// 抓拍图片
        /// </summary>
        /// <param name="index">设备索引</param>
        /// <returns></returns>
        public ResultEntity<string> SnapPlateNumImage(int index)
        {
            var result = ResultEntity<string>.Default(string.Empty, "开始抓拍图片");
            if (index < 0 || index >= mPlateNum.Count)
            {
                result = ResultEntity<string>.Error(string.Empty, "索引错误,抓拍图片失败!");
            }
            else
            {
                if (mPlateNum.Count == 0)
                {
                    result = ResultEntity<string>.Error(string.Empty, "索引错误,抓拍图片失败!");
                }
                else
                {
                    var plateVideo = mPlateNum[index];
                    var res = plateVideo.SnapImage();
                    if(res.Item1)
                    {
                        result = ResultEntity<string>.Success(res.Item2,"成功");
                    }
                    else
                    {
                        result = ResultEntity<string>.Error(res.Item2,"抓拍失败:"+ res.Item3);
                    }
                }
            }

            return result;
        }

        #endregion 车号识别获取车号、抓拍图片

        #region 浏览/停止浏览 视频
        /// <summary>
        /// 浏览监控视频
        /// </summary>
        /// <param name="channels">通道集合</param>
        /// <returns></returns>
        public ResultEntity PlayVideo(List<ChannelEntity> channels)
        {
            var result = ResultEntity.Default();
            try
            {
                if (mVideo == null)
                {
                    result = ResultEntity.Error("未开启此设备!");
                }
                else
                {
                    if(channels == null || channels.Count ==0)
                    {
                        result = ResultEntity.Error("设备预览参数无设置，预览失败!");
                    }
                    else
                    {
                        result = mVideo.Play(channels);
                    }
                }
            }
            catch(Exception ex)
            {
                result = ResultEntity.Error();
            }

            return result;
        }

        /// <summary>
        ///停止预览视频
        /// </summary>
        /// <returns></returns>
        public ResultEntity StopPlayVideo()
        {
            return mVideo.StopPlay();
        }
        #endregion 浏览视频/停止浏览

        #region 读卡写卡

        /// <summary>
        /// 读卡
        /// </summary>
        /// <param name="index">设备索引</param>
        /// <param name="entity">读卡参数</param>
        /// <returns></returns>
        public ResultEntity<ResultValEntity> ReadCard(CardType cardType,int index, ReadParamEntity entity)
        {
            ResultValEntity valEntity = new ResultValEntity();
            string name = CardTypeNameHelper.GetCardTypeName(cardType); 
            var result = ResultEntity<ResultValEntity>.Default(valEntity, "开始执行读取射频卡("+ name + ")的内容!");
            
            try
            {
                if (!mCards.Keys.Contains(cardType))
                {
                    result = ResultEntity<ResultValEntity>.Error(valEntity, "(" + name + ")读卡设备功能未开启，读卡失败!");
                    return result;
                }
                else
                {
                    var cards = mCards[cardType];
                    if (cards.Count == 0)
                    {
                        result = ResultEntity<ResultValEntity>.Error(valEntity, "(" + name + ")读卡设备功能未开启，读卡失败!");
                    }
                    else
                    {
                        if (index >= cards.Count)
                        {
                            result = ResultEntity<ResultValEntity>.Error(valEntity, "读卡索引[" + index + "],大于实际设备数[" + mCards.Count + "]");
                        }
                        else
                        {
                            if (entity == null)
                            {
                                result = ResultEntity<ResultValEntity>.Error(valEntity, "没有设置读卡参数,读卡失败!");
                            }
                            else
                            {
                                result = cards[index].Read(entity);
                            }
                        }
                    }
                }
             
            }
            catch(Exception ex)
            {
                result = ResultEntity<ResultValEntity>.Error(valEntity, "读卡异常,异常信息"+ex.Message+",堆栈信息:"+ex.StackTrace);
            }
            return result;
        }

        /// <summary>
        /// 写卡
        /// </summary>
        /// <param name="index">设备索引(从0 开始)</param>
        /// <param name="entity">写卡参数</param>
        /// <returns></returns>
        public ResultEntity WriteCard(CardType cardType,int index, WriteParamEntity entity)
        {
            var result = ResultEntity.Default("执行写卡操作!");
            string name = CardTypeNameHelper.GetCardTypeName(cardType);
            try
            {
                if (!mCards.Keys.Contains(cardType))
                {
                    result = ResultEntity.Error("没有开启射频卡功能,写卡失败!");
                    return result;
                }
                else
                {
                    var cards = mCards[cardType];
                    if (cards.Count == 0)
                    {
                        result = ResultEntity.Error("没有开启射频卡(" + name + ")功能,写卡失败!");
                    }
                    else
                    {
                        if (index >= cards.Count)
                        {
                            result = ResultEntity.Error("写卡索引[" + index + "],大于实际(" + name + ")设备数[" + cards.Count + "]");
                        }
                        else
                        {
                            if (entity == null)
                            {
                                result = ResultEntity.Error("没有设置写卡(" + name + ")参数, 写卡失败");
                            }
                            else
                            {
                                result = cards[index].Write(entity);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result = ResultEntity.Error("写卡异常,异常信息:"+ex.Message+",堆栈信息:"+ex.StackTrace);
            }

            return result;
        }

        #endregion 读写卡

        #region 显示信息到LED屏

        /// <summary>
        /// 显示消息到大屏
        /// </summary>
        /// <param name="index">设备索引号</param>
        /// <param name="content">消息的内容</param>
        /// <returns></returns>
        public ResultEntity ShowMsg(int index, string content)
        {
            var result = ResultEntity.Default();
           try
            {
                if(mLeds.Count == 0 )
                {
                    result = ResultEntity.Error("没有开启电子屏显示功能，显示消息失败。");
                }
                else
                {
                    if(index >=mLeds.Count)
                    {
                        result = ResultEntity.Error("电子屏设备索引[" + index + "],大于实际设备数[" + mLeds.Count + "]。");
                    }
                    else
                    {
                        if (content == null)
                        {
                            result = ResultEntity.Error("无效的显示内容,电子屏显示失败。");
                        }
                        else
                        {
                            result = mLeds[index].Show(content);
                        }
                    }
                }

            }
            catch(Exception ex)
            {
                result = ResultEntity.Error("电子屏显示异常,异常信息:" + ex.Message + ",堆栈信息:" + ex.StackTrace);
            }

           return result;
        }

        #endregion  显示信息到LED屏


        public void addLog(string msg)
        {
            throw new NotImplementedException();
        }
    }
}


